package org.Lin.dao;

import org.Lin.model.Admin;
import org.Lin.util.DatabaseUtil;

import java.sql.*;
import java.time.LocalDateTime;

public class AdminDAO {

    public void insert(Admin admin) throws SQLException {
        String sql = "INSERT INTO Admin(adminID, adminName, adminPassword, is_super_admin) VALUES (?, ?, ?, ?)";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, admin.getAdminID());
            stmt.setString(2, admin.getAdminName());
            stmt.setString(3, admin.getAdminPassword());
            stmt.setBoolean(4, admin.isSuperAdmin());
            stmt.executeUpdate();
        }
    }

    public Admin findByAdminID(int adminID) throws SQLException {
        String sql = "SELECT * FROM Admin WHERE adminID = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, adminID);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return mapToAdmin(rs);
            }
        }
        return null;
    }

    public void update(Admin admin) throws SQLException {
        String sql = "UPDATE Admin SET adminName = ?, adminPassword = ?, is_super_admin = ?, account_status = ? WHERE adminID = ?";
        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, admin.getAdminName());
            stmt.setString(2, admin.getAdminPassword());
            stmt.setBoolean(3, admin.isSuperAdmin());
            stmt.setString(4, admin.getAccountStatus());
            stmt.setInt(5, admin.getAdminID());
            stmt.executeUpdate();
        }
    }

    private Admin mapToAdmin(ResultSet rs) throws SQLException {
        Admin admin = new Admin();
        admin.setID(rs.getInt("ID"));
        admin.setAdminID(rs.getInt("adminID"));
        admin.setAdminName(rs.getString("adminName"));
        admin.setAdminPassword(rs.getString("adminPassword"));
        admin.setSuperAdmin(rs.getBoolean("is_super_admin"));
        admin.setCreatedAt(rs.getObject("created_at", LocalDateTime.class));
        admin.setLastLogin(rs.getObject("last_login", LocalDateTime.class));
        admin.setAccountStatus(rs.getString("account_status"));
        return admin;
    }
}
